package com.atguigu.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.excel.SubjectData;
import com.atguigu.eduservice.service.EduSubjectService;
import com.atguigu.servicebase.exxceptionhandler.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

public class SubjecyExceyListener extends AnalysisEventListener<SubjectData> {

    public EduSubjectService subjectService;//手动传过来，从上到下controller到service到
    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if(subjectData==null)
        {
            throw new GuliException(20001,"数据文件为空");
        }


        EduSubject existOnesubject = this.existOneSubject(subjectService,subjectData.getOneSubjectName());
        if(existOnesubject==null)
        {
            existOnesubject = new EduSubject();
            existOnesubject.setParentId("0");
            existOnesubject.setTitle(subjectData.getOneSubjectName());
            subjectService.save(existOnesubject);
        }
        //获取一级分类的id值
        String pid = existOnesubject.getId();

        EduSubject eduSubject = this.existTwoSubject(subjectService, subjectData.getTwoSubjectName(), pid);
        if(eduSubject ==null)
        {
            eduSubject = new EduSubject();
            eduSubject.setParentId(pid);
            eduSubject.setTitle(subjectData.getTwoSubjectName());
            subjectService.save(eduSubject);
        }
    }

    //一级分类不能重复添加
    private EduSubject existOneSubject(EduSubjectService eduSubjectService,String name)
    {
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id","0");
        EduSubject oneSubject = subjectService.getOne(wrapper);
        return oneSubject;
    }


    //二级不能重复添加
    private EduSubject existTwoSubject(EduSubjectService eduSubjectService,String name,String pid)
    {
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id",pid);
        EduSubject twoSubject = subjectService.getOne(wrapper);
        return twoSubject;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }

    public SubjecyExceyListener(EduSubjectService eduSubjectService){
        this.subjectService=eduSubjectService;
    }

    public SubjecyExceyListener(){}
}
